//
//  foodExchangeViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/7/5.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "foodExchangeViewController.h"
#import "VSinformationViewController.h"
#import "foodExchange.h"
#import "exchangeFoodTableViewCell.h"
#import "CollectionViewCell.h"

@interface foodExchangeViewController ()<UITextFieldDelegate,UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,assign)CGFloat y;
@property (nonatomic,weak)UITextField *searchTextField;
@property (nonatomic,weak)UIView *selectFoodView;//选择食物view
@property (nonatomic,weak)UIButton *exchangeBuutton;//交换按钮
@property (nonatomic,weak)UIView *qiaomenView;//小窍门view
@property (nonatomic,weak)UILabel *qiaomenNeirongLabel;
@property (nonatomic,weak)UIButton *xialaButton;
@property (nonatomic,assign)int clickXiaLaCount;
@property (nonatomic,weak)UILabel *tipsLabel;

@property (nonatomic,weak)UIScrollView *foodScrollView;
@property (nonatomic,strong)NSMutableArray *foodMutableArray;

@property (nonatomic,weak)UICollectionView *collcetionView;
@property (nonatomic,assign)int indexCount;
@property (nonatomic,assign)BOOL huadongFlag;

@property (nonatomic,strong)NSMutableArray *imageArrayM;
@property (nonatomic,strong)NSMutableArray *titleArrayM;

@property (nonatomic,weak)UILabel *xialaLabel;


@end

@implementation foodExchangeViewController

-(UILabel *)xialaLabel
{
    if(!_xialaLabel)
    {
        UILabel *xialaLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kDeviceHeight - 50, kDeviceWidth, 30)];
        xialaLabel.text = @"松手,加载更多数据!!";
        xialaLabel.textAlignment = NSTextAlignmentCenter;
        xialaLabel.font = [UIFont systemFontOfSize:14.0f];
        xialaLabel.textColor = YMColor(91, 91, 91);
        _xialaLabel = xialaLabel;
        [self.view addSubview:xialaLabel];
        xialaLabel.hidden = YES;
    }
    return _xialaLabel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"食物交换";
    self.view.backgroundColor = YMColor(245, 245, 245);
    self.clickXiaLaCount = 0;
    self.foodMutableArray = [NSMutableArray array];
    
    CGFloat h = (kDeviceWidth - 40) / 5.0 * 3 + 90;
    self.imageArrayM = [NSMutableArray array];
    self.titleArrayM = [NSMutableArray array];
    
    self.indexCount = 0;
    
    
    //初始化
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, kDeviceHeight - h + 1 , kDeviceWidth - 10, h - 1) collectionViewLayout:flowLayout];
    self.collcetionView = collectionView;
    //注册
    //    [collectionView registerClass:[CollectionViewCell class]forCellWithReuseIdentifier:@"collectionCell"];
    [self.collcetionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [self.view addSubview:collectionView];
    //    collectionView.backgroundColor = YMColor(245, 245, 245);
    collectionView.backgroundColor = [UIColor whiteColor];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.automaticallyAdjustsScrollViewInsets = NO; //控件无故偏移
    
    [self getFoodImageFromServices];
    
    [self searchTextFieldAndSearchButtonLayout];
    [self foodVSfoodLayout];
    [self littleQiaomenLayout];
    
    
    
}
//点击空白处收缩键盘
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.searchTextField resignFirstResponder];
}

/**搜索条和搜索按钮布局*/
-(void)searchTextFieldAndSearchButtonLayout
{
    self.y = 74;
    UITextField *searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, self.y, kDeviceWidth - 80, 30)];
    searchTextField.layer.cornerRadius = 8.0;
    searchTextField.layer.borderWidth = 1.0f;
    searchTextField.layer.borderColor = [YMColor(239, 180, 205)CGColor];
    searchTextField.textColor = YMColor(110, 110, 110);
    [searchTextField setValue:YMColor(206, 206, 206) forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.placeholder = @"请输入食物名称";
    searchTextField.delegate = self;
    self.searchTextField = searchTextField;
    searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:searchTextField];
    
    
    UIButton *searchButton = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth - 47, self.y + 4, 28, 28)];
    [searchButton setImage:[UIImage imageNamed:@"搜索btn"] forState:UIControlStateNormal];
    [self.view addSubview:searchButton];
    
    searchTextField.userInteractionEnabled = NO;
    searchButton.userInteractionEnabled = NO;
    
    self.y += searchTextField.frame.size.height + 10;
    
}

/**食物对比布局*/
-(void)foodVSfoodLayout
{
    UIView *foodVsFoodView = [[UIView alloc]initWithFrame:CGRectMake(0, self.y, kDeviceWidth, 70)];
    foodVsFoodView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:foodVsFoodView];
    
    CGFloat w = foodVsFoodView.frame.size.width;
    CGFloat h = foodVsFoodView.frame.size.height;
    
    UIImageView *logoImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, h / 3.0, h / 3.0, h / 3.0)];
    logoImage.image = [UIImage imageNamed:@"ssgl_VSicon"];
    [foodVsFoodView addSubview:logoImage];
    
    UILabel *foodLabel1 = [[UILabel alloc]initWithFrame:CGRectMake(w / 5.0, 10, w / 3.0, h / 2.0)];
    foodLabel1.textColor = YMColor(190, 74, 136);
    foodLabel1.text = @"食物对比";
    foodLabel1.font = [UIFont systemFontOfSize:18.0f];
    [foodVsFoodView addSubview:foodLabel1];
    
    UILabel *foodLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(w / 5.0, h / 3.0 + 10, w / 3.0, h / 2.0)];
    foodLabel2.text = @"食物营养素PK";
    foodLabel2.textColor = YMColor(162, 162, 162);
    foodLabel2.font = [UIFont systemFontOfSize:15.0f];
    [foodVsFoodView addSubview:foodLabel2];
    
    UIButton *vsButton = [[UIButton alloc]initWithFrame:CGRectMake(w / 3.0 * 2, 0, w / 3.0, h)];
    [vsButton setImage:[UIImage imageNamed:@"personal_》small"] forState:UIControlStateNormal];
    vsButton.imageEdgeInsets = UIEdgeInsetsMake(h / 3.0, w / 3.0 - h / 3.0 - 18, h / 3.0, 18);
    [foodVsFoodView addSubview:vsButton];
    [vsButton addTarget:self action:@selector(clickVSButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.y += foodVsFoodView.frame.size.height ;
}

-(void)clickVSButton
{
    VSinformationViewController *vs = [[VSinformationViewController alloc]init];
    [self.navigationController pushViewController:vs animated:YES];
}

/**小窍门和其内容布局*/
-(void)littleQiaomenLayout
{
    CGFloat h = kDeviceHeight - self.y - ((kDeviceWidth - 40) / 5.0 * 3 + 90);
    CGFloat w = kDeviceWidth;
    UIView *qiaomenView = [[UIView alloc]initWithFrame:CGRectMake(0, self.y, w, h)];
    self.qiaomenView = qiaomenView;
    [self.view addSubview:qiaomenView];
    
    UILabel *crosslabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, w, 1)];
    crosslabel.backgroundColor = YMColor(228, 228, 228);
    [qiaomenView addSubview:crosslabel];
    
    UILabel *qiaomenlabel = [[UILabel alloc]initWithFrame:CGRectMake((w - 91.58) * 0.5, 10, 91.58, 30)];
    qiaomenlabel.layer.cornerRadius = 15.0f;
    qiaomenlabel.clipsToBounds = YES;
    qiaomenlabel.text = @"小窍门";
    qiaomenlabel.textAlignment = NSTextAlignmentCenter;
    qiaomenlabel.textColor = [UIColor whiteColor];
    qiaomenlabel.backgroundColor = YMColor(147, 198, 49);
    [qiaomenView addSubview:qiaomenlabel];
    
    [self neirong:qiaomenView];
    
    UIButton *xialaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    xialaButton.frame = CGRectMake(kDeviceWidth / 2.0 - 35, self.qiaomenView.frame.size.height - 35, 70,35);
    //    CGFloat widthW = 36 - 4;
    //    xialaButton.imageEdgeInsets = UIEdgeInsetsMake(2, (w - widthW) * 0.5, 2, (w - widthW) * 0.5);
    [xialaButton setImage:[UIImage imageNamed:@"ssgl_arrowDOWN01"] forState:UIControlStateNormal];
    self.xialaButton = xialaButton;
    [qiaomenView addSubview:xialaButton];
    
    [xialaButton addTarget:self action:@selector(clickXialaButton) forControlEvents:UIControlEventTouchUpInside];
    
}

//部分内容
-(void)neirong:(UIView *)view
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    
    UILabel *neirongLabel = [[UILabel alloc]init];
    neirongLabel.frame = CGRectMake(10, 45, w - 20, h - 80);
    [self.qiaomenView addSubview:neirongLabel];
    neirongLabel.textColor = YMColor(113, 113, 113);
    neirongLabel.numberOfLines = 0;
    neirongLabel.font = [UIFont systemFontOfSize:13.0f];
    self.qiaomenNeirongLabel = neirongLabel;
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSDictionary *plistDic = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
    NSArray *titleArray = [plistDic objectForKey:@"xiaoqiaomen"];
    self.qiaomenNeirongLabel.text = titleArray[0];
    
}

//展开全部内容
-(void)allneirong:(UIView *)view
{
    CGFloat w = view.frame.size.width;
    CGFloat h = view.frame.size.height;
    UILabel *qingduLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
    NSDictionary *plistDic = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
    NSArray *titleArray = [plistDic objectForKey:@"xiaoqiaomen"];
    self.qiaomenNeirongLabel = qingduLabel;
    self.qiaomenNeirongLabel.text = titleArray[0];
    qingduLabel.textAlignment = NSTextAlignmentLeft;
    qingduLabel.font = [UIFont systemFontOfSize:13.0];
    NSDictionary * attribute2 = @{NSFontAttributeName:[UIFont systemFontOfSize:14.0]};
    CGSize size2 = [qingduLabel.text boundingRectWithSize:CGSizeMake(w - 20, h) options:NSStringDrawingUsesLineFragmentOrigin attributes:attribute2 context:nil].size;
    qingduLabel.lineBreakMode = NSLineBreakByCharWrapping;
    qingduLabel.numberOfLines = 0;
    qingduLabel.frame = CGRectMake(10, 35, w - 20, size2.height);
    qingduLabel.textColor = YMColor(95, 95, 95);
    
    [self.qiaomenView addSubview:qingduLabel];
    
    UILabel *tipsLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 35 + size2.height + (h - 70 - size2.height - 30) * 0.8, w - 20, 30)];
    tipsLabel.text = titleArray[1];
    tipsLabel.textColor = [UIColor redColor];
    self.tipsLabel = tipsLabel;
    tipsLabel.font = [UIFont systemFontOfSize:12.0f];
    tipsLabel.numberOfLines = 0;
    [view addSubview:tipsLabel];
}


-(void)clickXialaButton
{
    self.clickXiaLaCount ++;
    if(self.clickXiaLaCount % 2 == 1)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.qiaomenView.frame = CGRectMake(0, self.y, kDeviceWidth, kDeviceHeight - self.y);
            self.qiaomenView.backgroundColor = YMColor(245, 245, 245);
            //            CGFloat w = self.qiaomenView.frame.size.width;
            CGFloat h = self.qiaomenView.frame.size.height;
            self.xialaButton.frame = CGRectMake(kDeviceWidth * 0.5 - 35, h - 35, 70, 35);
            [self.xialaButton setImage:[UIImage imageNamed:@"ssgl_arrowUP01"] forState:UIControlStateNormal];
        }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.qiaomenNeirongLabel removeFromSuperview];
            [self allneirong:self.qiaomenView];
        });
    }
    else
    {
        [UIView animateWithDuration:0.5 animations:^{
            CGFloat h = kDeviceHeight - self.y - ((kDeviceWidth - 40) / 5.0 * 3 + 90);
            self.xialaButton.frame = CGRectMake(kDeviceWidth * 0.5 - 35, h - 35, 70, 35);
            [self.xialaButton setImage:[UIImage imageNamed:@"ssgl_arrowDOWN01"] forState:UIControlStateNormal];
            self.qiaomenView.frame = CGRectMake(0, self.y, kDeviceWidth, h);
        }];
        [self.qiaomenNeirongLabel removeFromSuperview];
        [self neirong:self.qiaomenView];
        [self.tipsLabel removeFromSuperview];
        
    }
}


/**从网上下载食物图片*/
-(UIImage *)downimageFromInternet:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:str];
    NSData *resultData1 = [NSData dataWithContentsOfURL:url];
    UIImage *img1 = [UIImage imageWithData:resultData1];
    return img1;
}




#pragma mark - UIScrollViewDelegate实现方法-
// scrollView滚动时执行
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y >= fmaxf(.0f, scrollView.contentSize.height - scrollView.frame.size.height) + 50) //x是触发操作的阀值
    {
        //触发上拉刷新
        
        if(self.huadongFlag == NO)
        {
            self.xialaLabel.hidden = NO;
        }
    }
    else
    {
        self.xialaLabel.hidden = YES;
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //    NSLog(@"scrollViewWillBeginDragging");
    //    [self.foodMutableArray removeAllObjects];
    
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView.contentOffset.y >= fmaxf(.0f, scrollView.contentSize.height - scrollView.frame.size.height) + 50) //x是触发操作的阀值
    {
        //触发上拉刷新
        if(self.huadongFlag == NO)
        {
            [self getFoodImageFromServices];
            
        }
    }
    
}

/**从服务器上获取要交换的食物图片*/
-(void)getFoodImageFromServices
{
    self.indexCount ++;
    //    YMLog(@"self.indexCount = %d",self.indexCount);
    [MBProgressHUD showMessage:@"正在拼命加载中，请稍后..."];
    
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/findexchangeFoods.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"pageSize=15&pageIndex=%@&foodType=%@",[NSString stringWithFormat:@"%d",self.indexCount],self.foodType];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            //                YMLog(@"dict = %@",dict);
            if([[dict objectForKey:@"code"] isEqualToString:@"0"])
            {
                NSArray *dataarray = [dict objectForKey:@"data"];
                for (NSDictionary *food in dataarray) {
                    foodExchange *fff = [foodExchange foodInfoWithDict:food];
                    [self.foodMutableArray addObject:fff];
                }
                //                [self addImageToArrayMAndAddTitleToTitleArrayM];
                [UIView animateWithDuration:0.01 animations:^{
                    [self.collcetionView reloadData];
                }];
            }
            if([[dict objectForKey:@"code"]isEqualToString:@"1"])
            {
                [MBProgressHUD showError:@"数据已加载完毕!!!"];
                self.huadongFlag = YES;
                
            }
        }
    }];
}

//将图片存到数组中
-(void)addImageToArrayMAndAddTitleToTitleArrayM
{
    for (foodExchange *fff in self.foodMutableArray) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *image = [self downimageFromInternet:fff.imgSrc];
            dispatch_async(dispatch_get_main_queue(), ^{
                //加载图片
                [self.imageArrayM addObject:image];
                //设置label文字
                
            });
            [self.titleArrayM addObject:fff.name];
        });
        
    }
    
}

//每个section的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.foodMutableArray.count;
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * CellIdentifier = @"UICollectionViewCell";
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    foodExchange *fff = self.foodMutableArray[indexPath.row];
    CGFloat w = cell.frame.size.width;
    CGFloat h = cell.frame.size.height;
    
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, w, w)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, w, w, h - w)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textColor = YMColor(95, 95, 95);
    
    NSURL *url = [[NSURL alloc]initWithString:fff.imgSrc];
    [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zonghe"]];
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    //    UIImage *cachedImage = [manager imageWithURL:url]; // 将需要缓存的图片加载进来
    [manager downloadImageWithURL:url options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        //        NSLog(@"显示当前进度");
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        //        NSLog(@"下载完成");
        
        
    }];
    
    //    [imageView sd_setImageWithURL:url];
    label.text = fff.name;
    
    
    for (id subView in cell.contentView.subviews)
    {
        [subView removeFromSuperview];
    }
    [cell.contentView addSubview:label];
    [cell.contentView addSubview:imageView];
    
    [cell sizeToFit];
    
    return cell;
}



#pragma mark -- UICollectionViewDelegate
//设置每个 UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat spaceX = 5.0f;
    CGFloat lw = (kDeviceWidth - spaceX * 8) / 5.0;
    CGFloat lh = lw + 25;
    return CGSizeMake(lw, lh);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0,0);
}

//定义每个UICollectionView 的纵向间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}


-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"______--------%@",@(indexPath.row).description);
    foodExchange *fff = self.foodMutableArray[indexPath.row];
    
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    if(self.exchangeBuutton)
    {
        [self.exchangeBuutton removeFromSuperview];
    }
    CGFloat w = cell.frame.size.width;
    CGFloat h = cell.frame.size.height;
    CGFloat x = cell.frame.origin.x;
    CGFloat y = cell.frame.origin.y;
    
    UIButton *huanButton = [[UIButton alloc]initWithFrame:CGRectMake(x, y, w, h - 25)];
    [huanButton setImage:[UIImage imageNamed:@"ssgl_changefood"] forState:UIControlStateNormal];
    self.exchangeBuutton = huanButton;
    [collectionView addSubview:huanButton];
    huanButton.tag = [fff.code intValue];
    [huanButton addTarget:self action:@selector(clickHuanButton:) forControlEvents:UIControlEventTouchUpInside];
}

//点击了换按钮
-(void)clickHuanButton:(UIButton *)btn
{
    //
    [self foodExchangeFoodInformationToServices:[NSString stringWithFormat:@"%lu",btn.tag]];
}

-(void)foodExchangeFoodInformationToServices:(NSString *)newFoodCode
{
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/exchangeFood.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&lastFoodCode=%@&newFoodCode=%@&weight=%@&foodItemId=%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"],self.foodCode,newFoodCode,self.foodWeight,self.foodID];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            //            YMLog(@"dict = %@",dict);
            if([[dict objectForKey:@"code"] isEqualToString:@"0"])
            {
                [MBProgressHUD showSuccess:@"更换成功!!"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [passValue passValue].exchangeFoodFlag = YES;
                    [self.navigationController popViewControllerAnimated:YES];
                    
                });
            }
            else
            {
                [MBProgressHUD showError:@"失败!!"];
            }
        }
    }];
}



@end
